package com.sea.physical.controller;

import com.sea.physical.entity.Unusual;

import com.sea.physical.service.UnusualService;
import com.codecrane.core.power.service.DictDetailService;
import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sea.supply.service.SupplierService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/sea/physical/unusual")
public class UnusualController {

    @Autowired
    private UnusualService unusualService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private DictDetailService dictDetailService;

    /**
     * 物流管理主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/main")
    public String main(Model model) {
        getModel(model);
        return "/sea/physical/unusual/main";
    }

    /**
     * 物流管理主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/supply/main")
    public String supplyMain(Model model) {
        getModel(model);
        return "/sea/supply/unusual/main";
    }
    /**
     * 财务管理主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/finance/main")
    public String financeMain(Model model,@RequestParam("flag")Integer flag) {
        getModel(model);
        model.addAttribute("flag",flag);
        return "/sea/finance/unusual/main";
    }

    /**
     * 新增页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/addpage")
    public String addpage(Model model) {
        getModel(model);
        return "/sea/physical/unusual/add";
    }

    /**
     * 修改页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/supply/editPage")
    public String editPage(Model model,@RequestParam("id")Integer id) {
        getModel(model);
        model.addAttribute("unusual",unusualService.findById(id));
        return "/sea/supply/unusual/edit";
    }

    private void getModel(Model model){
        //供应商
        model.addAttribute("supplier",supplierService.findByCnd(null));
        //国家字典
        model.addAttribute("unusual",dictDetailService.findByTypeCode("unusual_reason", null));
    }

    @ResponseBody
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public AjaxReturn save(Unusual unusual) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try{

            if (null != unusual && unusualService.save(unusual) > 0) {
                result.setOk(true).setMsg("保存成功！");
            }
        }catch (RuntimeException e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }
    @ResponseBody
    @RequestMapping(value = "/usave", method = RequestMethod.POST)
    public AjaxReturn usave(Unusual unusual) {
        AjaxReturn result = Ajax.fail().setMsg("修改失败！");
        try{

            if (null != unusual && unusualService.usave(unusual) > 0) {
                result.setOk(true).setMsg("修改成功！");
            }
        }catch (RuntimeException e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByCnd")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     Unusual unusual) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<Unusual> list = unusualService.findByCnd(unusual);
        PageInfo<Unusual> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }

    @ResponseBody
    @RequestMapping("/delete")
    public AjaxReturn deleteByIds(@RequestParam("id") Integer id) {
        AjaxReturn result = Ajax.fail().setMsg("操作失败！");
        if (null!=id && unusualService.delete(id) >0 ) {
            result.setOk(true).setMsg("删除成功");
        }
        return result;
    }

    @RequestMapping(value = "/export", method = RequestMethod.GET)
    @ResponseBody
    public void export(HttpServletResponse response, Unusual unusual) {
        List<Unusual> list =unusualService.findByCnd(unusual);
        String[] title = {"柜号", "供应商", "异常原因", "币种", "原币", "人民币", "实际装柜时间", "备注(物流)","操作人(物流)","实际付款","付款时间","操作人(供应链)","备注(供应链)","操作人(财务)","状态" };

        String fileName = "异常费用" + DateUtils.dateToString(new Date(), "yyyyMMdd") + ".xls";
        String sheetName = "异常费用";
        String[][] content = new String[list.size()][15];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            Unusual obj = list.get(i);
            content[i][0] = obj.getCreatePlanNo();
            content[i][1] = obj.getSupplierName();
            content[i][2] = obj.getUnusualReason();
            content[i][3] = obj.getUnusualMoneyType();
            content[i][4] = obj.getUnusualMoneyOriginal()+"";
            content[i][5] = obj.getUnusualMoney()+"";
            content[i][6] = obj.getUnusualTime();
            content[i][7] = obj.getOperateRemark();
            content[i][8] = obj.getOperateName();
            content[i][9] = obj.getSupplyPaymentMoney()+"";
            content[i][10] = obj.getSupplyPaymentTime();
            content[i][11] = obj.getSupplyOperateName();
            content[i][12] = obj.getSupplyRemark();
            content[i][13] = obj.getFinanceOperateName();
            if(obj.getFlag().equals(2)){
                content[i][14] ="已付款";
            }else {
                content[i][14] ="未付款";
            }
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
